<template>
  <div class="playedu-tree">
    <!-- 全部分类按钮 -->
    <div
      :class="[
        'mb-8 category-label',
        selectKey.length === 0 ? 'active' : ''
      ]"
      @click="handleSelect([], '')"
    >
      <div class="j-b-flex">
        <span>全部{{ props.text }}</span>
      </div>
    </div>

    <!-- 树形组件 -->
    <a-tree
      v-if="treeData.length > 0"
      :tree-data="treeData"
      :selectedKeys="selectKey"
      @select="onSelect"
      @expand="onExpand"
    >
      <template #title="{ title }">
        <span class="tree-title-elli">{{ title }}</span>
      </template>
      <template #switcherIcon>
        <i class="iconfont icon-icon-fold c-gray" />
      </template>
    </a-tree>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from "vue";
import { resourceCategory } from "@/api/index";

interface Option {
  key: string | number;
  title: any;
  children?: Option[];
}

interface PropInterface {
  type: string;
  text: string;
  selected: any;
  onUpdate: (keys: any, title: any) => void;
}

const props = defineProps<PropInterface>();

const treeData = ref<Option[]>([]);
const selectKey = ref<string[]>([]);

// 监听 props.selected 更新选中
watch(
  () => props.selected,
  (val) => {
    if (val && val.length > 0) {
      selectKey.value = val;
    }
  },
  { immediate: true }
);

// 构造树形数据
const checkArr = (categories: Record<number, any[]>, id: number): Option[] => {
  const arr: Option[] = [];
  const list = categories?.[id] ?? []; // 如果 categories[id] 不存在，返回 []

  if (!Array.isArray(list) || list.length === 0) {
    return arr;
  }

  for (let i = 0; i < list.length; i++) {
    const cate = list[i];
    if (!cate) continue;

    const name = cate.name ?? "未命名";

    if (!categories[cate.id]) {
      arr.push({
        title: name,
        key: String(cate.id),
      });
    } else {
      arr.push({
        title: name,
        key: String(cate.id),
        children: checkArr(categories, cate.id),
      });
    }
  }

  return arr;
};

// 初始化树数据
const loadCategories = async () => {
  try {
    const res = await resourceCategory.resourceCategoryList();
    const categories = res.data.categories;
    if (categories && JSON.stringify(categories) !== "{}") {
      const newArr = checkArr(categories, 0);
      if (props.type === "no-cate") {
        newArr.unshift({
          key: 0,
          title: "未分类",
        });
      }
      treeData.value = newArr;
    }
  } catch (err) {
    console.error("获取分类失败：", err);
  }
};

onMounted(() => {
  loadCategories();
});

// 点击选择
const onSelect = (selectedKeys: any, info: any) => {
  let label = "全部" + props.text;
  if (info?.node?.title && typeof info.node.title === "string") {
    label = info.node.title;
  }
  props.onUpdate(selectedKeys, label);
  selectKey.value = selectedKeys;
};

const handleSelect = (selectedKeys: any, title: any) => {
  props.onUpdate(selectedKeys, title);
  selectKey.value = selectedKeys;
};

// 展开事件（预留）
const onExpand = (keys: any, info: any) => {};
</script>
